//
//  YZENetwork.m
//  YZENetwork
//
//  Created by zjs on 17/3/14.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import "YZENetwork.h"
#import "NSDictionary+PropertyCode.h"
#import "NSObject+Add.h"
#import <AFNetworking.h>
@implementation YZENetwork

{
    AFHTTPSessionManager *manager;
}

-(instancetype )init{
    
    if (self = [super init]) {
        manager=[AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
        ((AFJSONResponseSerializer*)manager.responseSerializer).removesKeysWithNullValues = YES;
        //        _manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
        
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //        _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    
    return self;
}

+(instancetype)sharedInstace{
    static YZENetwork *sharedInstace = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (sharedInstace == nil) {
            sharedInstace = [[[self class] alloc] init];
            sharedInstace.isShowLog = NO;
        }
    });
    
    return sharedInstace;
}


/**
 post
 
 @param url url
 @param parameters 请求参数
 @param delegate delegate
 @param tag 请求tag
 @param successBlock 成功回调
 */
-(void)postRequestWithUrl:(NSString*)url parameters:(id)parameters delegate:(id)delegate requestTag:(int)tag successBlock:(SuccessBlock)successBlock{
    
    if ([delegate respondsToSelector:@selector(OnStartWithRequestTag:) ] ) {
        [delegate OnStartWithRequestTag:tag];
    }
    
    [self printfLog:url];
    [self printfLog:parameters];
    
    //设置头部信息
    [self setHttpURLHeader];
    
    [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        [self printfLog: [NSString stringWithFormat:@"[POST请求返回]%@", responseObject]];
        if ([delegate respondsToSelector:@selector(OnFinishWithRequestTag:) ] ) {
            [delegate OnFinishWithRequestTag:tag];
        }
        NSDictionary *dic = responseObject;
        NSInteger result = [dic[@"result"] integerValue];
        if (result == SUCCESS_CODE) {
            if (successBlock) {
                successBlock(dic[@"data"]);
            }
            
            //打印返回bean
            if (_isShowPropertyCode) {
                [(NSDictionary*)(dic[@"data"]) propertyCode];
            }
            
        }else{
            
            if ([delegate respondsToSelector:@selector(OnFail:errorCode:requestTag:) ] ) {
                [delegate OnFail:dic[@"message"] errorCode:[dic[@"result"] integerValue] requestTag:tag];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if ([delegate respondsToSelector:@selector(OnFinishWithRequestTag:) ] ) {
            [delegate OnFinishWithRequestTag:tag];
        }
        
        [self printfLog:[NSString stringWithFormat:@"errorCode--%d--domain--%@",error.code,error.domain]];
        
        if ([delegate respondsToSelector:@selector(OnFail:errorCode:requestTag:) ] ) {
            [delegate OnFail:[error code]==NSURLErrorTimedOut?@"请求超时，请稍后重试":@"网络连接异常，请稍后再试" errorCode:[error code] requestTag:tag];
        }
    }];
    
}


-(void)postRequestRegisterWithUrl:(NSString*)url parameters:(id)parameters delegate:(id)delegate requestTag:(int)tag successBlock:(SuccessBlock)successBlock{
    if ([delegate respondsToSelector:@selector(OnStartWithRequestTag:) ] ) {
        [delegate OnStartWithRequestTag:tag];
    }
    
    [self printfLog:url];
    [self printfLog:parameters];
    
    //设置头部信息
    [self setHttpURLHeader];
    
    [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        [self printfLog:responseObject];
        
        if ([delegate respondsToSelector:@selector(OnFinishWithRequestTag:) ] ) {
            [delegate OnFinishWithRequestTag:tag];
        }
        NSDictionary *dic = responseObject;
        NSInteger result = [dic[@"result"] integerValue];
        if (result == SUCCESS_CODE) {
            if (successBlock) {
                successBlock(dic);
            }
            //打印返回bean
            if (_isShowPropertyCode) {
                [(NSDictionary*)(dic[@"data"]) propertyCode];
            }
            
        }else{
            
            if ([delegate respondsToSelector:@selector(OnFail:errorCode:requestTag:) ] ) {
                [delegate OnFail:dic[@"message"] errorCode:[dic[@"result"] integerValue] requestTag:tag];
                [UIView showToastWindowWithMessage:dic[@"message"]];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if ([delegate respondsToSelector:@selector(OnFinishWithRequestTag:) ] ) {
            [delegate OnFinishWithRequestTag:tag];
        }
        
        [self printfLog:[NSString stringWithFormat:@"errorCode--%d--domain--%@",error.code,error.domain]];
        
        if ([delegate respondsToSelector:@selector(OnFail:errorCode:requestTag:) ] ) {
            [delegate OnFail:[error code]==NSURLErrorTimedOut?@"请求超时，请稍后重试":@"网络连接异常，请稍后再试" errorCode:[error code] requestTag:tag];
            [UIView showToastWindowWithMessage:[error code]==NSURLErrorTimedOut?@"请求超时，请稍后重试":@"网络连接异常，请稍后再试"];
        }
    }];

}

/**
 get请求
 
 @param url <#url description#>
 @param parameters <#parameters description#>
 @param delegate <#delegate description#>
 @param tag <#tag description#>
 @param successBlock <#successBlock description#>
 */
-(void)getRequestWithUrl:(NSString*)url parameters:(id)parameters delegate:(id)delegate requestTag:(int)tag successBlock:(SuccessBlock)successBlock{
    
    if ([delegate respondsToSelector:@selector(OnStartWithRequestTag:) ] ) {
        [delegate OnStartWithRequestTag:tag];
    }
    
    [self printfLog:[NSString stringWithFormat:@"[发送GET]%@", url]];
    [self printfLog:parameters];
    
    //设置头部信息
    [self setHttpURLHeader];
    
    [manager GET:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self printfLog:[NSString stringWithFormat:@"[GET请求返回]%@", responseObject]];
        if ([delegate respondsToSelector:@selector(OnFinishWithRequestTag:) ] ) {
            [delegate OnFinishWithRequestTag:tag];
        }
        NSDictionary *dic = responseObject;
        NSInteger result = [dic[@"result"] integerValue];
        if (result == SUCCESS_CODE) {
            if (successBlock) {
                successBlock(dic[@"data"]);
            }
            
            //打印返回bean
            if (_isShowPropertyCode) {
                [(NSDictionary*)(dic[@"data"]) propertyCode];
            }
            
        }else{
            
            if ([delegate respondsToSelector:@selector(OnFail:errorCode:requestTag:) ] ) {
                [delegate OnFail:dic[@"description"] errorCode:[dic[@"result"] integerValue] requestTag:tag];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self printfLog:[NSString stringWithFormat:@"errorCode--%d--domain--%@",error.code,error.domain]];
        if ([delegate respondsToSelector:@selector(OnFinishWithRequestTag:) ] ) {
            [delegate OnFinishWithRequestTag:tag];
        }
        
        if ([delegate respondsToSelector:@selector(OnFail:errorCode:requestTag:) ] ) {
            [delegate OnFail:[error code]==NSURLErrorTimedOut?@"请求超时，请稍后重试":@"网络连接异常，请稍后再试" errorCode:[error code] requestTag:tag];
        }
    }];
    
}

/**
 PUT
 
 @param url url
 @param parameters 请求参数
 @param delegate delegate
 @param tag 请求tag
 @param successBlock 成功回调
 */
-(void)putRequestWithUrl:(NSString*)url parameters:(id)parameters delegate:(id)delegate requestTag:(int)tag successBlock:(SuccessBlock)successBlock{
    
    if ([delegate respondsToSelector:@selector(OnStartWithRequestTag:) ] ) {
        [delegate OnStartWithRequestTag:tag];
    }
    
    [self printfLog:url];
    [self printfLog:parameters];
    
    //设置头部信息
    [self setHttpURLHeader];
    
    [manager PUT:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self printfLog:[NSString stringWithFormat:@"[PUT请求返回]%@",responseObject]];
        if ([delegate respondsToSelector:@selector(OnFinishWithRequestTag:) ] ) {
            [delegate OnFinishWithRequestTag:tag];
        }
        NSDictionary *dic = responseObject;
        NSInteger result = [dic[@"result"] integerValue];
        if (result == SUCCESS_CODE) {
            if (successBlock) {
                successBlock(dic[@"data"]);
            }
            
            //打印返回bean
            if (_isShowPropertyCode) {
                [(NSDictionary*)(dic[@"data"]) propertyCode];
            }
            
        }else{
            
            if ([delegate respondsToSelector:@selector(OnFail:errorCode:requestTag:) ] ) {
                [delegate OnFail:dic[@"message"] errorCode:[dic[@"result"] integerValue] requestTag:tag];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if ([delegate respondsToSelector:@selector(OnFinishWithRequestTag:) ] ) {
            [delegate OnFinishWithRequestTag:tag];
        }

        [self printfLog:[NSString stringWithFormat:@"errorCode--%d--domain--%@",error.code,error.domain]];
        
        if ([delegate respondsToSelector:@selector(OnFail:errorCode:requestTag:) ] ) {
            [delegate OnFail:[error code]==NSURLErrorTimedOut?@"请求超时，请稍后重试":@"网络连接异常，请稍后再试" errorCode:[error code] requestTag:tag];
        }
    }];
}

/**
 DELETE
 
 @param url url
 @param parameters 请求参数
 @param delegate delegate
 @param tag 请求tag
 @param successBlock 成功回调
 */
-(void)deleteRequestWithUrl:(NSString*)url parameters:(id)parameters delegate:(id)delegate requestTag:(int)tag successBlock:(SuccessBlock)successBlock{
    
    if ([delegate respondsToSelector:@selector(OnStartWithRequestTag:) ] ) {
        [delegate OnStartWithRequestTag:tag];
    }
    
    [self printfLog:url];
    [self printfLog:parameters];
    
    //设置头部信息
    [self setHttpURLHeader];
    [manager DELETE:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self printfLog: [NSString stringWithFormat:@"[DELETE请求返回]%@", responseObject]];
        if ([delegate respondsToSelector:@selector(OnFinishWithRequestTag:) ] ) {
            [delegate OnFinishWithRequestTag:tag];
        }
        
        NSDictionary *dic = responseObject;
        NSInteger result = [dic[@"result"] integerValue];
        if (result == SUCCESS_CODE) {
            if (successBlock) {
                successBlock(dic[@"data"]);
            }
            
            //打印返回bean
            if (_isShowPropertyCode) {
                [(NSDictionary*)(dic[@"data"]) propertyCode];
            }
            
        }else{
            
            if ([delegate respondsToSelector:@selector(OnFail:errorCode:requestTag:) ] ) {
                [delegate OnFail:dic[@"message"] errorCode:[dic[@"result"] integerValue] requestTag:tag];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if ([delegate respondsToSelector:@selector(OnFinishWithRequestTag:) ] ) {
            [delegate OnFinishWithRequestTag:tag];
        }
        
        [self printfLog:[NSString stringWithFormat:@"errorCode--%d--domain--%@", error.code,error.domain]];
        
        if ([delegate respondsToSelector:@selector(OnFail:errorCode:requestTag:) ] ) {
            [delegate OnFail:[error code]==NSURLErrorTimedOut?@"请求超时，请稍后重试":@"网络连接异常，请稍后再试" errorCode:[error code] requestTag:tag];
        }
    }];
    /*
    [manager PUT:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    */
}


/**
 设置请求头部信息
 */
-(void)setHttpURLHeader{
    
    //手机系统版本
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // 当前应用名称
    //    NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    //    NSLog(@"当前应用名称：%@",appCurName);
    // 当前应用软件版本  比如：1.0.1
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970]*1000;
    
    [manager.requestSerializer setValue:appCurVersion forHTTPHeaderField:@"app-version"];
    [manager.requestSerializer setValue:phoneVersion forHTTPHeaderField:@"os-version"];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"%f",time] forHTTPHeaderField:@"timestamp"];
    
    if (_dicHTTPHeaderField) {
        [_dicHTTPHeaderField enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            // key:属性名
            [manager.requestSerializer setValue:obj forHTTPHeaderField:key];
            
            
        }];
    }
    
}






-(void)printfLog:(id)log{
    if (_isShowLog) {
        NSLog(@"%@",log);
    }
}


/**
 取消所有网络请求
 */
-(void)cancelNetwork{
    [manager.operationQueue cancelAllOperations];
}
@end

